package com.doubao.common.service;

import com.doubao.common.utils.RedisTemplateFactory;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisLockService {

    private RedisTemplate<String, Object> redisTemplate;
    private final ThreadLocal<String> lockValueThreadLocal = new ThreadLocal<>();
    
    @PostConstruct
    public void init() {
        this.redisTemplate = RedisTemplateFactory.getRedisTemplate();
        log.info("RedisLockService使用RedisTemplateFactory获取RedisTemplate");
    }

    /**
     * 获取分布式锁
     * @param lockKey 锁键
     * @param expireTime 过期时间
     * @param timeUnit 时间单位
     * @return 是否成功获取锁
     */
    public boolean acquireLock(String lockKey, long expireTime, TimeUnit timeUnit) {
        String value = UUID.randomUUID().toString();
        Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, value, expireTime, timeUnit);

        if (Boolean.TRUE.equals(result)) {
            lockValueThreadLocal.set(value);
            return true;
        }
        return false;
    }

    /**
     * 释放分布式锁
     * @param lockKey 锁键
     * @return 是否成功释放锁
     */
    public boolean releaseLock(String lockKey) {
        String value = lockValueThreadLocal.get();
        if (value == null) {
            return false;
        }

        String currentValue = (String) redisTemplate.opsForValue().get(lockKey);
        if (value.equals(currentValue)) {
            redisTemplate.delete(lockKey);
            lockValueThreadLocal.remove();
            return true;
        }
        return false;
    }
}